//
//  LHNetWorking.m
//  CurbApp
//
//  Created by LH on 16/6/20.
//  Copyright © 2016年 LH. All rights reserved.
//

#import "LHNetWorking.h"
#import "AFNetworking.h"
#import "AddressHeader.h"
#import "SecurityUtil.h"

#import "RSASignVerify.h"

@implementation LHNetWorking
/**
 * 下载验证
 *
 * @param 字典类型参数
 * @param 成功回调
 * @param 失败回调
 */
+ (void)getDownloadValidation:(id)parmas whileSuccess:(SuccessBlock)successBlock orFail:(FailBlock)failBlock{
     NSLog(@"下载验证参数:%@",parmas);
    AFHTTPSessionManager *manager =[self newAFManager];
    [manager POST:LDownloadValidationURL parameters:parmas progress:^(NSProgress * _Nonnull uploadProgress) {
        
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        NSString *resStr=  [[NSString alloc] initWithData:responseObject encoding:NSUTF8StringEncoding];
        NSLog(@"%@",resStr);
        if(resStr.length>0){
        NSData *jsonData=[self stringDeleteString:resStr];
        NSDictionary *dataDic1 = [NSJSONSerialization JSONObjectWithData:jsonData options:1 error:nil];
        NSLog(@"下载验证获取数据:%@",dataDic1);
        successBlock(dataDic1);
        }
        
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        failBlock(error);
        
    }];
//    [self getRequestParmas:parmas URL:LDownloadValidationURL whileSuccess:^(id gReponsObject) {
//        NSString *resStr=  [[NSString alloc] initWithData:gReponsObject encoding:NSUTF8StringEncoding];
//        NSLog(@"%@",resStr);
//        if(resStr.length>0){
//            NSData *jsonData=[self stringDeleteString:resStr];
//            NSDictionary *dataDic1 = [NSJSONSerialization JSONObjectWithData:jsonData options:1 error:nil];
//            successBlock(dataDic1);
//        };
//        
//    } orFail:^(id errer) {
//        failBlock(errer);
//    }];
    
    
}
/**
 * 登录请求
 *
 * @param 字典类型参数
 * @param 成功回调
 * @param 失败回调
 */
+ (void)getLoginRequest:(id)parmas whileSuccess:(SuccessBlock)successBlock orFail:(FailBlock)failBlock{

   
    [self getRequestParmas:parmas URL:LLoginURL whileSuccess:^(id gReponsObject) {
        successBlock(gReponsObject);
    } orFail:^(id errer) {
        failBlock(errer);
    }];
}
//请求公共方法
+(void)getRequestParmas:(id)parmas URL:(id)url whileSuccess:(GSuccessBlock)successBlock orFail:(GFailBlock)failBlock{
    AFHTTPSessionManager *manager =[self newAFManager];
    parmas=[self paramMD5Encryption:parmas];
     NSLog(@"请求接口:%@",url);
     NSLog(@"请求参数:%@",parmas);
    [manager POST:url parameters:parmas progress:^(NSProgress * _Nonnull uploadProgress) {
        
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        NSString *resStr=  [[NSString alloc] initWithData:responseObject encoding:NSUTF8StringEncoding];
        NSLog(@"%@",resStr);
        if(resStr.length>0){
            NSData *jsonData=[self stringDeleteString:resStr];
            NSDictionary *dataDic1 = [NSJSONSerialization JSONObjectWithData:jsonData options:1 error:nil];
            NSLog(@"结果数据:%@",dataDic1);
            successBlock(dataDic1);
        }
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        failBlock(error);
    }];
    
}

//参数MD5签名
+(NSDictionary *)paramMD5Encryption:(NSDictionary *)param{
    NSMutableDictionary *dic=[[NSMutableDictionary alloc]initWithDictionary:param];
    [dic setValue:TID forKey:@"tid"];
    [dic setValue:SECRETKEY forKey:@"secretKey"];
    NSString *dicString=[self dictionaryToJson:dic];
    NSLog(@"dic=%@",dic);
    NSLog(@"dicString=%@",dicString);
    
    //RSASignVerify* handler = [RSASignVerify sharedInstance];
    NSString *signStr=[SecurityUtil md5s:dicString]; //[handler signMD5String:dicString]; //[SecurityUtil md5:dicString];
    [dic setValue:@"" forKey:@"secretKey"];
    [dic setValue:signStr forKey:@"sign"];
    

    return dic;
}
//字典转json字符串
+(NSString*)dictionaryToJson:(NSMutableDictionary *)dic

{
//    NSError *parseError = nil;
//    NSData *jsonData = [NSJSONSerialization dataWithJSONObject:dic options:NSJSONWritingPrettyPrinted error:&parseError];
//    return [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
    NSArray *keys = dic.allKeys;
    NSArray *sortedKeys = [keys sortedArrayUsingComparator:^NSComparisonResult(id  _Nonnull obj1, id  _Nonnull obj2) {
        return (NSComparisonResult)[obj1 compare:obj2 options:NSLiteralSearch];
    }];
    
    NSMutableArray *jsonStrArray = [NSMutableArray arrayWithCapacity:1];
    for (NSString *key in sortedKeys) {
        NSString *jsonElement = [NSString stringWithFormat:@"%@=%@",key,dic[key]];
        [jsonStrArray addObject:jsonElement];
    }
    
    NSString *jsonStr = [NSString stringWithFormat:@"{%@}",[jsonStrArray componentsJoinedByString:@", "]];
    NSLog(@"jsonStrjsonStr===%@",jsonStr);
    return jsonStr;
}
//斜杠JSON字符串转译
+(NSData *) stringDeleteString:(NSString *)str
{
    NSMutableString *str1 = [NSMutableString stringWithString:str];
    NSString *character = nil;
    for (int i = 0; i < str1.length; i ++) {
        character = [str1 substringWithRange:NSMakeRange(i, 1)];
        if ([character isEqualToString:@"\\"])
            [str1 deleteCharactersInRange:NSMakeRange(i, 1)];
    }
    [str1 deleteCharactersInRange:NSMakeRange(0,1)];
    [str1 deleteCharactersInRange:NSMakeRange(str1.length-1,1)];
    NSLog(@"str1:%@",str1);
    NSString *str111=[NSString stringWithFormat:@"%@",str1];
    NSLog(@"str111:%@",str111);
    NSData *jasonData = [str1 dataUsingEncoding:NSUTF8StringEncoding];
    return jasonData;
}
#pragma AFHTTPSessionManager 公共
+(AFHTTPSessionManager *)newAFManager{
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    manager.requestSerializer = [AFHTTPRequestSerializer serializer];
    manager.responseSerializer = [AFHTTPResponseSerializer serializer];
    //    manager.responseSerializer.acceptableContentTypes = [NSSet setWithObject:@"text/plain"];
    //    [manager.requestSerializer setValue:userUUID forHTTPHeaderField:@"UUID-TOKEN"];
    
    return manager;
}
@end
